<template>
    <div>
        <h2>基本设置</h2>
        <div class="user-info">
            <Form :model="formValidate" label-position="top" :rules="ruleCustom" ref="formValidate">
                <FormItem label="角色">
                    <span v-if="formValidate.roleid ==1"></span>
                    <span v-if="formValidate.roleid ==2"></span>
                    <span v-if="formValidate.roleid ==3"></span>
                </FormItem>
                <FormItem label="姓名">
                    <i-input v-model="formValidate.realname" style="width:120px;"></i-input>
                </FormItem>
                <FormItem label="性别">
                    <RadioGroup v-model="gender">
                        <Radio label="true">男</Radio>
                        <Radio label="false">女</Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem label="生日">
                    <DatePicker v-model="formValidate.birthday" placement="bottom-end" placeholder="未设置"></DatePicker>
                </FormItem>
                <FormItem label="手机" prop="mobile">
                    <i-input v-model="formValidate.mobile" :maxlength="11"></i-input>
                </FormItem>
                <FormItem label="邮箱">
                    <i-input v-model="formValidate.email" :maxlength="20" placeholder="未设置" style="width:200px;"></i-input>
                </FormItem>
                <FormItem label="个性签名">
                    <i-input v-model="formValidate.signature" type="textarea" :rows="2" placeholder="未设置"></i-input>
                </FormItem>
                <div>
                    <Button type="primary" class="btn" @click="handleUpdateUser('formValidate')">更新基本信息</Button>
                </div>
            </Form>
            <div class="user-info-right">
                <p>头像</p>
                <div>
                    <img :src="formValidate.headicon ? formValidate.headicon : defaultAvatar">
                </div>
                <div class="upload-img">
                    <Button type="primary" class="btn">
                        <input class="input-file" type="file" @change="uploadImg">
                        上传头像
                    </Button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { updateUser, uploadImage } from '@/api/user';
export default {
    name: 'UserManagement',
    data() {
        const validatePass = (rule, value, callback) => {
            if (!/^1(3|4|5|7|8)\d{9}$/.test(value)) {
                callback(new Error('请输入正确手机号码'));
            } else {
                callback();
            }
        };
        return {
            formValidate: {
                realname: '',
                name: '',
                birthday: '',
                mobile: '',
                email: '',
                WeChat: '',
                signature: '',
                headicon: ''
            },
            ruleCustom: {
                mobile: [{ validator: validatePass, trigger: 'blur' }]
            },
            gender: '1',
            defaultAvatar: require('@/assets/images/defaultAvatar.jpg')
        };
    },
    methods: {
        // 设置用户信息
        setUserInfo() {
            const userInfo = JSON.parse(sessionStorage.getItem('user'));
            this.formValidate = {
                signature: userInfo.signature,
                realname: userInfo.realname,
                mobile: userInfo.mobile,
                birthday: userInfo.birthday,
                email: userInfo.email,
                headicon: userInfo.headicon
            };
            this.gender = userInfo.gender + '';
        },
        // 更新用户信息
        handleUpdateUser(name) {
            this.$refs[name].validate(valid => {
                if (valid) {
                    const id = JSON.parse(sessionStorage.getItem('user')).uid;
                    const data = { gender: this.gender, ...this.formValidate, id };
                    delete data.headicon;
                    updateUser(data).then(res => {
                        const user = JSON.parse(sessionStorage.getItem('user'));
                        const newUser = { ...user, ...res.data };
                        sessionStorage.setItem('user', JSON.stringify(newUser));
                        this.$Message.success('更新成功');
                    });
                }
            });
        },
        // 更新头像
        uploadImg(e) {
            const name = e.target.value;
            const size = e.target.files[0].size / 1024;
            const fileName = name.substring(name.lastIndexOf('.') + 1).toLowerCase();
            if (fileName !== 'png' && fileName !== 'jpg' && fileName !== 'jpeg' && fileName !== 'gif') {
                this.$Message.error('图片格式错误');
            } else if (size > 500) {
                this.$Message.error('请选择500kB以内的图片');
            } else {
                const id = JSON.parse(sessionStorage.getItem('user')).uid;
                let formData = new FormData();
                formData.append('id', id);
                formData.append('avatar', e.target.files[0]);
                uploadImage(formData).then(res => {
                    this.formValidate.headicon = res.data.headicon;
                    const user = JSON.parse(sessionStorage.getItem('user'));
                    user.headicon = res.data.headicon;
                    sessionStorage.setItem('user', JSON.stringify(user));
                    const id = JSON.parse(sessionStorage.getItem('user')).uid;
                    const data = { gender: this.gender, ...this.formValidate, id };
                    updateUser(data).then(res => {
                        const userArr = JSON.parse(sessionStorage.getItem('user'));
                        const newUser = { ...userArr, ...res.data, headicon: user.headicon };
                        sessionStorage.setItem('user', JSON.stringify(newUser));
                        this.$Message.success('更新成功');
                    });
                });
            }
        }
    },
    mounted() {
        this.setUserInfo();
    }
};
</script>

<style lang="less" scoped>
.user-info {
    padding-top: 20px;
    display: flex;
    .btn {
        background: #5ab1ef;
        border: none;
    }
    .user-info-right {
        margin-left: 200px;
        text-align: center;
        div {
            img {
                margin-top: 20px;
                width: 100px;
                height: 100px;
                border-radius: 50%;
                overflow: hidden;
            }
        }
    }
    .form-item-width {
        width: 200px;
    }
    .upload-img {
        margin-top: 20px;
        position: relative;
        cursor: pointer;
        .input-file {
            position: absolute;
            top: 0;
            left: 0;
            background: red;
            width: 90px;
            opacity: 0;
            padding: 5px;
        }
    }
}
</style>
